package com.mdxq.mall.order.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.mdxq.mall.order.dto.OrderSearchDTO;
import com.mdxq.mall.order.dto.UpdateDeliveryDTO;
import com.mdxq.mall.order.dto.UpdateNoteDTO;
import com.mdxq.mall.order.dto.UpdateReceiverInfoDTO;
import com.mdxq.mall.order.service.OrderItemService;
import com.mdxq.mall.order.service.OrderOperateHistoryService;
import com.mdxq.mall.response.R;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.mdxq.mall.order.entity.Order;
import com.mdxq.mall.order.service.OrderService;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 订单表 控制层。
 *
 * @author zdy
 * @since 2025-01-19
 */
@RestController
@RequestMapping("/api/v1/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 添加订单表。
     *
     * @param order 订单表
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("save")
    public boolean save(@RequestBody Order order) {
        return orderService.save(order);
    }

    /**
     * 根据主键批量删除订单表。
     *
     * @param ids 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @PostMapping ("delete")
    public R delete(@RequestParam String ids, @RequestHeader("Authorization") String token) {
        //分割成数组，转换成集合，批量删除
        return R.ok(orderService.removeByIds(Arrays.asList(ids.split(",")),token));
    }

    /**
     * 根据主键更新订单表。
     *
     * @param order 订单表
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("update")
    public boolean update(@RequestBody Order order) {
        return orderService.updateById(order);
    }

    /**
     * 查询所有订单表。
     *
     * @return 所有数据
     */
    @GetMapping("list")
    public List<Order> list() {
        return orderService.list();
    }

    /**
     * 根据订单表主键获取详细信息。
     *
     * @param id 订单表主键
     * @return 订单表详情
     */
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private OrderOperateHistoryService operateHistoryService;
    @GetMapping("getInfo/{id}")
    public R getInfo(@PathVariable Long id) {
        Order order = orderService.getById(id);
        if (order!=null){
            QueryWrapper queryWrapper = QueryWrapper.create().eq("order_id",id);
            order.setOrderItemList(orderItemService.list(queryWrapper));
            QueryWrapper queryWrapper1 = QueryWrapper.create().eq("order_id",id);
            order.setHistoryList(operateHistoryService.list(queryWrapper1));
        }
        return R.ok(order);
    }

    /**
     * 分页查询订单表。
     *
     * @param page 分页对象
     * @param dto 查询条件
     * @return 分页对象
     */
    //这个模式对象可以用来判断字符串是不是手机号
    private Pattern pattern = Pattern.compile("^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$");
    @GetMapping("page")
    public R page(Page<Order> page,OrderSearchDTO dto) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StrUtil.isNotBlank(dto.getOrderSn())){
            queryWrapper.eq("order_sn",dto.getOrderSn());
        }else {
            if (StrUtil.isNotBlank(dto.getReceiverKeyword())){
                if (pattern.matcher(dto.getReceiverKeyword()).matches()){//如果是手机号，matches返回true，否则返回false
                    queryWrapper.eq("receiver_phone",dto.getReceiverKeyword());

                }else {
                    queryWrapper.eq("receiver_name",dto.getReceiverKeyword());
                }

            }
            if (dto.getStatus()!=null){
                queryWrapper.eq("status",dto.getStatus());
            }
            if (dto.getOrderType()!=null){
                queryWrapper.eq("order_type",dto.getOrderType());
            }
            if (dto.getSourceType()!=null){
                queryWrapper.eq("source_type",dto.getSourceType());
            }
            if (dto.getCreateTime()!=null){
                queryWrapper.between("create_time",
                        LocalDateTime.of(dto.getCreateTime(), LocalTime.MIN),
                        LocalDateTime.of(dto.getCreateTime(), LocalTime.MAX));//从2025-1-20 00:00:00到2025-1-20 23:59:59
            }

//        queryWrapper.eq("receive_keyword",dto.getReceiveKeyword());
        }

        return R.ok(orderService.page(page,queryWrapper));
    }
    @PostMapping("update/receiverInfo")
    public R receiverInfo(@RequestBody UpdateReceiverInfoDTO dto, @RequestHeader("Authorization") String token){
        Order order = BeanUtil.copyProperties(dto,Order.class);
        order.setId(dto.getOrderId());
        boolean f = orderService.updateReceiverInfo(order,token);
        return R.ok(f);
    }
    @PostMapping("update/note")
    public R note(UpdateNoteDTO dto, @RequestHeader("Authorization") String token){
        boolean f = orderService.updateNote(dto,token);
        return R.ok(f);
    }
    @PostMapping("update/delivery")
    public R updateDelivery(@RequestBody List<UpdateDeliveryDTO> dtoList, @RequestHeader("Authorization") String token){
        boolean f = orderService.updateDelivery(dtoList,token);
        return R.ok(f);
    }
    @PostMapping("update/close")
    public R close(@RequestParam String ids,@RequestParam String note,@RequestHeader("Authorization") String token){
        boolean f = orderService.updateClose(ids,note,token);
        return R.ok(f);
    }
}
